//var serverPath = 'http://192.168.1.188:8081/';
var serverPath = 'https://www.huanledang.com/';
const key      = '144195ce29c940ed8c5c765c19bf5ee6';

/**
 * 封装Request 请求
 * @param opt
 */
function request(opt) {

  // set token
  var token = wx.getStorageSync("token");
  if (token && opt.url.indexOf('token=') == -1) {
    if (opt.url.indexOf('?') == -1) {
      opt.url += "?token=" + token;
    } else {
      opt.url += "&token=" + token;
    }
  }
  if (key && opt.url.indexOf('key=') == -1) {
    if (opt.url.indexOf('?') == -1) {
      opt.url += "?key=" + key;
    } else {
      opt.url += "&key=" + key;
    }
  }
  
  //加载loading
  wx.showNavigationBarLoading();

  //调用ajax
  wx.request({
    method: opt.method || 'GET',
    header: {
      token: token || ''
    },
    url: serverPath + opt.url,
    data: opt.data,
    success: function (res) {

      //HTTP 状态码为200
      if (res.statusCode == 200) {

        //业务返回成功
        if (res.data.code == 2000) {
          if (opt.success) {
            opt.success(res.data.data, res.data);
          }
        } 
        //请求CODE 非2000
        else {
          console.warn(res.data);
          wx.showModal({
            content: res.data.msg,
            showCancel: false
          })
        }
      } 
      //微信异常
      else {
        console.error(res);
        /*
        wx.showModal({
          title: '微信异常',
          content: res.code,
          showCancel: false
        })*/
        /*opt.fail();*/
        
        wx.showModal({
          content: '服务器异常',
          showCancel: false,
          confirmText: 'OK',
          success: function (res) {
  
          }
        })
      }
    },
    fail: function (res) {

      opt.fail();

      wx.showModal({
        content: '网络通信错误',
        showCancel: false,
        confirmText:'OK',
        success: function (res) {
          if (res.confirm) {
            //request(opt);
            console.log('用户点击确定');
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      })
    },
    complete: function () {
      wx.hideNavigationBarLoading();
    }
  })
}

module.exports = {
  serverPath: serverPath,
  request: request,
  key: key
}